//
//  SemaphoreViewController.m
//  TEXT
//
//  Created by liubo on 2023/10/9.
//  Copyright © 2023 刘博. All rights reserved.
//

#import "SemaphoreViewController.h"
#import "HittestView.h"

@interface SemaphoreViewController ()

@property (nonatomic, strong) HittestView *testView;

@end

@implementation SemaphoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.testView = [[HittestView alloc] init];
    [self.view addSubview:self.testView];
    __weak SemaphoreViewController *weakSelf = self;
    NSBlockOperation *operation_1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"哈哈哈执行执行1111");
          [weakSelf loadGoods];
        NSLog(@"哈哈哈执行33333");
          [weakSelf loadCredit];
        sleep(3);
        NSLog(@"哈哈哈哈执行44444");
      }];
    
      NSBlockOperation *operation_2 = [NSBlockOperation blockOperationWithBlock:^{
          NSLog(@"哈哈哈执行555555");
      }];
      //设置依赖
      [operation_2 addDependency:operation_1];
   
      //创建队列并添加任务
      //如果为YES。阻塞当前线程、直到队列该次添加的所有操作全部执行完成。
      //如果为NO。就是批量添加操作而已。
      NSOperationQueue *queue = [[NSOperationQueue alloc]init];
      [queue addOperations:@[operation_2,operation_1] waitUntilFinished:NO];
    // Do any additional setup after loading the view.
}

- (void)loadGoods
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
      
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_semaphore_signal(semaphore);
        NSLog(@"哈哈哈哈执行执行2");
    });
       //若计数为0则一直等待
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
}

- (void)loadCredit
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_semaphore_signal(semaphore);

    });
       //若计数为0则一直等待
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

- (void)dealloc{
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
